﻿using System;
using System.Text.RegularExpressions; 


namespace Cstudy.Tools
{
    public class RegexTools
    {
        //验证后缀名 
        public bool IsValidPostfix(string strIn)
        {
            return Regex.IsMatch(strIn, @"\.(?i:gif|jpg)$");
        }

        //验证字符是否在s至e之间 
        public bool IsValidByte(string strIn,int s,int e)
        {
            return Regex.IsMatch(strIn, @"^.[a-zA-Z]\w{" + s.ToString() + "," + e.ToString() + "}$");
        }

        //验证IP 
        public bool IsValidIp(string strIn)
        {
            return Regex.IsMatch(strIn, @"^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$");
        }

        //验证是否为小数 
        public bool IsValidDecimal(string strIn)
        {

            return Regex.IsMatch(strIn, @"[0].\d{1,2}|[1]");
        }

        //验证是否为电话号码 
        public bool IsValidTel(string strIn)
        {
            return Regex.IsMatch(strIn, @"(\(\d{3,4}\)|\d{3,4}-|\s)?\d{7,14}");
        }

        //验证年月日 
        public bool IsValidDate(string strIn)
        {
            return Regex.IsMatch(strIn, @"^2\d{3}-(?:0?[1-9]|1[0-2])-(?:0?[1-9]|[1-2]\d|3[0-1])(?:0?[1-9]|1\d|2[0-3]):(?:0?[1-9]|[1-5]\d):(?:0?[1-9]|[1-5]\d)$");
        }
        //验证Email地址 
        public bool IsValidEmail(string strIn)
        {
            // Return true if strIn is in valid e-mail format. 
            return Regex.IsMatch(strIn, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
        }

        //dd-mm-yy 的日期形式代替 mm/dd/yy 的日期形式。 
        public string MDYToDMY(String input)
        {
            return Regex.Replace(input, "\\b(?\\d{1,2})/(?\\d{1,2})/(?\\d{2,4})\\b", "${day}-${month}-${year}");
        }

        //搜索输入字符串并返回所有 href=“...”值 
        public string DumpHrefs(String inputString)
        {
            Regex r;
            Match m;
            r = new Regex("href\\s*=\\s*(?:\"(?<1>[^\"]*)\"|(?<1>\\S+))",
             RegexOptions.IgnoreCase | RegexOptions.Compiled);
            for (m = r.Match(inputString); m.Success; m = m.NextMatch())
            {
                return ("Found href " + m.Groups[1]);
            }
            return null;
        } 

    }
}
